package com.kumi.controller;


import com.alibaba.fastjson.JSON;
import com.kumi.controller.BaseController;
import com.kumi.exception.ApiException;
import com.kumi.util.DigestUtil;
import com.kumi.viewmodel.ApiResult;
import com.kumi.viewmodel.MapResult;
import com.kumi.viewmodel.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static com.kumi.db.getConnection.getConnection;

/**
 * @author  on 2016-07-11.
 */
@RestController
public class LoginController extends BaseController {
    @RequestMapping(value = "login")
    public ApiResult login(String loginId, String password) {
        List<User> userList = select();
        String a="2";
        for (User user : userList) {

            if (loginId.equals(user.getUsername()) && password.equals(user.getPassword())) {
                a="1";
                break;
            }
            else {
                a="2";
            }

        }



        MapResult mapResult = new MapResult();
        mapResult.put("token", DigestUtil.Encrypt("0:" + loginId));
        mapResult.put("a",a);
        return mapResult;
    }



    public static List<User> select(){

        String sql = "SELECT username,password ,phonenumber FROM myusers";
        List<User> userList = new ArrayList<User>();
        PreparedStatement preparedStatement;

        try {
            preparedStatement = getConnection().prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                User loginUser = new User();
                loginUser.setUsername(resultSet.getString("username"));
                loginUser.setPassword(resultSet.getString("password"));
                userList.add(loginUser);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userList;

    }



}
